package www.lagou.app;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import www.lagou.entity.AccountBean;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 转账交易测试
 */
public class TestTransction {

    //数据库连接对象
    private static  Connection con = null;

    //连接池创建QueryRunner
    private static QueryRunner  queryRunner = null;

    public static void main(String[] args) {
        //1.连接池创建QueryRunner
        queryRunner = new QueryRunner();

        //2.查询sql
        String sql = "select * from account";
        try {
            //3.获取连接
            con = DruidUtils.getConnection();

            //3.执行查询sql，返回JavaBean对象 List
            List<AccountBean> query = queryRunner.query(con,sql, new BeanListHandler<AccountBean>(AccountBean.class));

            //4.开始转账
            transaction(query.get(0),query.get(1));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 转账
     * @param accountBean
     * @param accountBean1
     */
    private static void transaction(AccountBean accountBean, AccountBean accountBean1) throws SQLException {
        if(accountBean.getBalance() < 5000){
            System.out.println("余额不足");
        }else{
            con.setAutoCommit(false);
            String sql1 = "update account set balance = balance - 5000 where card = '1122334455'";
            String sql2 = "update account set balance = balance + 5000 where card = '55443332211'";
            queryRunner.update(con,sql1);
            queryRunner.update(con,sql2);
            //插入一条转账记录
            LocalDateTime localDateTime = LocalDateTime.now();
            DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formatDate = localDateTime.format(date);
            String sql3 = "insert into TRANSACTION (cardid,tratype,tramoney,tradate) values('1122334455','转出',5000,'"+formatDate+"')";
            String sql4 = "insert into TRANSACTION (cardid,tratype,tramoney,tradate) values('55443332211','转入',5000,'"+formatDate+"')";
            System.out.println(sql3);
            System.out.println(sql4);
            queryRunner.update(con,sql3);
            queryRunner.update(con,sql4);
            con.commit();
        }
    }
}
